<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-row>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-col :span="24">
          <el-form-item label="机构名称" prop="orgName">
            <el-input v-model="queryParams.orgName" placeholder="请输入机构名称" clearable @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
          <el-form-item label=" " prop="showDisabled">
            <el-checkbox @change="checkShowFullName">显示全路径</el-checkbox>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="机构类型" prop="orgKindId">
            <!--        <el-select v-model="queryParams.orgKindId"
                               placeholder="公司/中心/部门/人员"
                               clearable
                               multiple
                               size="small">
                      <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SA_ORGMANAGER_KIND_ID)"
                                 :key="dict.value" :label="dict.label" :value="dict.value"/>
                    </el-select>-->
            <!--        <el-checkbox-group v-model="queryParams.orgKindId" @change="queryOrgKindIdChange">-->
            <el-checkbox @change="queryOrgKindIdChange" checked :true-label="dict.value"
                         :false-label="dict.value + '_cancel'"
                         v-for="dict in orgKindIdList"
                         :label="dict.label"></el-checkbox>
            <!--        </el-checkbox-group>-->
          </el-form-item>
          <el-form-item label="岗位名称" prop="managerDefineName">
            <!--        <el-select v-model="queryParams.managerDefineIds"
                               placeholder="请选择管理岗位"
                               clearable
                               multiple
                               size="small">
                      <el-option v-for="dict in this.orgManagerDefine"
                                 :key="dict.code" :label="dict.name" :value="dict.code"/>
                    </el-select>-->
            <el-checkbox @change="queryManagerDefineChange" checked :true-label="dict.code"
                         :false-label="dict.code + '_cancel'" v-for="dict in orgManagerDefine"
                         :label="dict.name"></el-checkbox>
          </el-form-item>
        </el-col>

      </el-form>
    </el-row>
    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-thumb" size="mini" @click="handleTestMatrix">验证
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['sa:oporg-manager-matrix-config:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading"
              v-if="refreshTable"
              row-key="id"
              border
              :tree-props="{children: 'children'}"
              @cell-click="handleEditPerson"
              :cell-style="getCellBackColor"
              :data="list">
      <!--      <el-table-column label="ID" align="center" prop="id"/>-->
      <!--      <el-table-column label="机构ID" align="center" prop="orgId"/>-->
      <!--      <el-table-column label="机构全路径" align="center" prop="orgFullId"/>-->
      <el-table-column label="名称" align="left" prop="name"/>
      <el-table-column label="类型" align="center" prop="orgKindId" max-width="60">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.SA_ORGMANAGER_KIND_ID" :value="scope.row.orgKindId"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="组织管理岗ID" align="center" prop="managerDefineId"/>-->
      <!--      <el-table-column label="岗位" align="center" prop="managerDefineName"/>-->

      <el-table-column v-if="refreshColumn" v-for="item in this.filterShowManagerDefine" :property="item.code"
                       align="left">
        <template slot="header" slot-scope="scope">
          {{ item.name }}
        </template>
        <template slot-scope="scope">
          <el-tooltip v-if="!showFullName" placement="top">
            <div slot="content">
              {{ filterManagerConfigText(scope.row, item.code, 'orgFullName') }}
            </div>
            <span>
              {{ filterManagerConfigText(scope.row, item.code) }}
            </span>
          </el-tooltip>
          <span v-else>{{ filterManagerConfigText(scope.row, item.code) }}</span>
        </template>
      </el-table-column>

    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>


    <!--      矩阵人员配置窗口-->
    <el-dialog title="人员设置" :visible.sync="openConfigDialog" width="800px" height="300" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleUserPicker">添加</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-tickets" size="mini" @click="handleCopyDataValues">复制
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-document" size="mini" @click="handlePasteDataValues">粘贴
          </el-button>
        </el-col>
      </el-row>

      <el-table v-loading="configPersonListLoading"
                height="200"
                :data="editConfigInfo.dataValues"
      >
        <el-table-column label="姓名" align="center" prop="orgName" show-overflow-tooltip/>
        <el-table-column label="路径" align="left" prop="orgFullName" min-width="200" show-overflow-tooltip/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="100">
          <template v-slot="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteConfigPerson(scope.row.orgId)"
                       v-hasPermi="['sa:oporg-manager-matrix-config:delete']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitConfigForm">确 定</el-button>
        <el-button @click="closeConfigDialog">关闭</el-button>
      </div>
    </el-dialog>
    <!--      矩阵人员测试窗口-->
    <el-dialog title="人员设置" :visible.sync="openTestDialog" width="800px" height="300" append-to-body>
      <el-row>
        <el-form :model="testParams" ref="testParamsForm" size="small" :inline="true" label-width="68px">
          <el-col :span="24">
            <el-form-item label="组织" prop="orgName">
              <el-input v-model="testParams.orgName" placeholder="请选择机构" clearable disabled>
                <el-button slot="append" icon="el-icon-search" @click="handleChooseOrg"></el-button>
              </el-input>
            </el-form-item>
            <el-form-item label="岗位" prop="managerDefineId">
              <el-select v-model="testParams.managerDefineId" placeholder="请选择管理岗位" clearable size="small">
                <el-option v-for="dict in this.orgManagerDefine" :key="dict.code" :label="dict.name"
                           :value="dict.code"/>
              </el-select>
            </el-form-item>
            <el-form-item label="岗位所属组织" prop="managerDefineId">
              <el-select v-model="testParams.orgKindId" placeholder="岗位所属组织" clearable size="small">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.SA_ORGMANAGER_KIND_ID)"
                           :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleQueryMatrixPerson">查询</el-button>
              <el-button icon="el-icon-refresh" @click="resetTestQuery">重置</el-button>
            </el-form-item>

          </el-col>
        </el-form>
      </el-row>

      <el-table v-loading="testTableLoading"
                height="200"
                :data="testMatrixPersonList">
        <el-table-column label="姓名" align="center" prop="name" show-overflow-tooltip/>
        <el-table-column label="路径" align="left" prop="fullName" min-width="200" show-overflow-tooltip/>
        <el-table-column label="岗位所属组织" align="left" prop="managerOrgName" show-overflow-tooltip/>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeTestDialog">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="人员选择" :visible.sync="openUserPicker" width="1200px" append-to-body style="text-align: center;">
      <SaUserPicker :org-kind-id="saPersonPickerOrgKind" @complete="getUserList" @close="openUserPicker = false"/>
    </el-dialog>

    <el-dialog title="人员选择" :visible.sync="openTestUserPicker" width="1200px" append-to-body
               style="text-align: center;">
      <SaUserPicker :multiple="false" :org-kind-id="testPersonPickerOrgKind" @complete="testOrgChooseConfig"
                    @close="openTestUserPicker = false"/>
    </el-dialog>

  </div>
</template>

<script>
import {
  createOporgManagerMatrixConfig,
  updateOporgManagerMatrixConfig,
  deleteOporgManagerMatrixConfig,
  getOporgManagerMatrixConfig,
  getOrgManagerMatrixPerson,
  getOporgManagerMatrixConfigData,
  exportOporgManagerMatrixConfigExcel
} from "@/api/sa/oporgManagerMatrixConfig";
import {getOporgManagerDefineAllList} from "@/api/sa/oporgManagerDefine";
import {COMMON_TREE, CommonStatusEnum} from "@/utils/constants";
import {createRoleFolderUser} from "@/api/sa/role";
import SaUserPicker from '@/components/SaPersonPicker';
import {OrgKindEnum} from "@/utils/constants";
import {DICT_TYPE} from "@/utils/dict";

export default {
  name: "OporgManagerMatrixConfig",
  components: {SaUserPicker},
  data() {
    return {
      // 遮罩层
      loading: true,
      refreshTable: true,
      refreshColumn: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 组织管理矩阵人员落位表 列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        orgId: null,
        orgFullId: null,
        orgName: null,
        orgKindId: null,
        managerDefineId: null,
        managerDefineName: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 岗位定义列表
      orgManagerDefine: [],
      // 组织orgKindId 类型
      orgKindIdList: [],

      // 列表中显示的岗位数组
      filterShowManagerDefine: [],
      // 列表中显示的组织类型
      filterShowOrgKindId: [],
      // 所有岗位的集合,key=>code
      orgManagerDefineMap: {},
      // 所有岗位的使用范围集合,key=>orgKindId
      orgManagerDefineOrgKindMap: {},
      openConfigDialog: false,
      openUserPicker: false,
      configPersonListLoading: false,
      editConfigInfo: {
        matrixId: null,
        orgId: null,
        orgFullId: null,
        orgName: null,
        orgKindId: null,
        managerDefineId: null,
        managerDefineName: null,
        dataValues: null,
      },
      // 当前编辑的行
      editTableRows: {},
      // 当前编辑的列
      editTableCell: {},
      // 人员选择器，可选择的组织类型：岗位和人员
      saPersonPickerOrgKind: [OrgKindEnum.Position.code, OrgKindEnum.Psm.code].join(","),
      // 列表中是否显示人员或岗位全路径
      showFullName: false,
      // 拼装后的矩阵列表数据
      matrixData: [],
      // 复制的单元格数据
      copyDataValues: null,
      // 矩阵测试窗口
      openTestDialog: false,
      testParams: {},
      testParamsForm: {},
      testTableLoading: false,
      testMatrixPersonList: [],
      // 矩阵测试，人员选择窗口
      openTestUserPicker: false,
      testPersonPickerOrgKind: [OrgKindEnum.Org.code, OrgKindEnum.Center.code, OrgKindEnum.Dept.code, OrgKindEnum.Position.code, OrgKindEnum.Psm.code].join(","),
    };
  },
  created() {
    this.matrixId = this.$route.params && this.$route.params.matrixId;
    this.orgKindIdList = this.filterShowOrgKindId = this.getDictDatas(DICT_TYPE.SA_ORG_KIND_ID)
    this.getList();
    this.initManagerDefine()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getOporgManagerMatrixConfigData({matrixId: this.matrixId}).then(response => {
        this.list = []
        let orgList = response.data.orgList
        let dataList = response.data.dataList
        let dataMap = {}
        dataList.forEach(item => {
          item.dataValues = item.dataValues && JSON.parse(item.dataValues) || []
          dataMap[item.orgId + "_" + item.managerDefineId] = item
        })
        orgList.forEach(org => {
          this.orgManagerDefine.forEach(def => {
            org[def.code] = dataMap[org.id + "_" + def.code]
          })
        })
        this.matrixData = orgList
        let newData = this.filterMatrixData(this.matrixData)
        this.list = this.handleTree(newData, undefined, undefined, undefined, COMMON_TREE.ROOT.id)
      }).finally(() => {
        this.loading = false;
      });
    },

    getCellBackColor(data) {
      let row = data.row
      let column = data.column
      if (!this.orgManagerDefineMap[column.property]) {
        return ""
      }
      if (!!this.orgManagerDefineMap[column.property]
        && this.orgManagerDefineMap[column.property].orgKindId.indexOf(row.orgKindId) > -1) {
        return ""
      } else {
        return "background-color:whitesmoke"
      }
    },

    filterManagerConfigText(row, managerDefineId, field) {
      let dataValues = row[managerDefineId] && row[managerDefineId].dataValues
      let text = []
      if (dataValues && dataValues.length > 0) {
        dataValues.forEach(item => {
          if (!!field) {
            text.push(item[field])
          } else if (!this.showFullName) {
            text.push(item.orgName)
          } else {
            text.push(item.orgFullName)
          }
        })
        return text.join(";  ")
      }
      return ""
    },

    initManagerDefine() {
      getOporgManagerDefineAllList({status: CommonStatusEnum.ENABLE}).then(response => {
        this.orgManagerDefine = response.data
        this.filterShowManagerDefine = [...this.orgManagerDefine]
        this.orgManagerDefine.forEach(item => {
          this.orgManagerDefineMap[item.code] = item
          this.orgManagerDefineOrgKindMap[item.orgKindId] = item
        })
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        orgId: undefined,
        orgFullId: undefined,
        orgName: undefined,
        orgKindId: undefined,
        managerDefineId: undefined,
        managerDefineName: undefined,
        dataValues: undefined,
        status: undefined,
        version: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    filterMatrixData(data) {
      let newData = []
      let orgManagerOrgKindMap = {}
      let existsDef = {}
      this.filterShowOrgKindId.forEach(item => {
        existsDef[item.value] = item
      })
      this.orgKindIdList.forEach(item => {
        orgManagerOrgKindMap[item.value] = item
      })
      data.forEach(item => {
        if (existsDef[item.orgKindId] || !orgManagerOrgKindMap[item.orgKindId]) {
          newData.push(item)
        }
      })
      return newData
    },
    // 机构类型显示与隐藏
    queryOrgKindIdChange(val) {
      let newColumn = []
      let existsDef = {}
      if (val.indexOf("cancel") > 0) {
        //隐藏类型
        let changeValue = val.split('_')
        this.filterShowOrgKindId.forEach(item => {
          if (item.value != changeValue[0]) {
            existsDef[item.value] = item
          }
        })
      } else {
        //显示类型
        existsDef[val] = true
        this.filterShowOrgKindId.forEach(item => {
          existsDef[item.value] = item
        })
      }

      let orgManagerOrgKindMap = {}
      this.orgKindIdList.forEach(item => {
        orgManagerOrgKindMap[item.value] = item
        if (existsDef[item.value]) {
          newColumn.push(item)
        }
      })

      this.filterShowOrgKindId = [...newColumn]

      let newData = this.filterMatrixData(this.matrixData)
      this.list = this.handleTree(newData, undefined, undefined, undefined, COMMON_TREE.ROOT.id)
      this.refreshTable = false
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    // 岗位列显示与隐藏
    queryManagerDefineChange(val) {
      // 隐藏列
      let newColumn = []
      let existsDef = {}
      if (val.indexOf("cancel") > 0) {
        let changeValue = val.split('_')
        this.filterShowManagerDefine.forEach(item => {
          if (item.code != changeValue[0]) {
            existsDef[item.code] = item
          }
        })
      } else {
        //显示列
        existsDef[val] = true
        this.filterShowManagerDefine.forEach(item => {
          existsDef[item.code] = item
        })
      }
      this.orgManagerDefine.forEach(item => {
        if (existsDef[item.code]) {
          newColumn.push(item)
        }
      })
      this.filterShowManagerDefine = [...newColumn]
      this.refreshColumn = false
      this.$nextTick(() => {
        this.refreshColumn = true
      })
    },
    checkShowFullName(val) {
      this.showFullName = val
      this.refreshColumn = false
      this.$nextTick(() => {
        this.refreshColumn = true
      })
    },

    /** 导出按钮操作 */
    handleExport() {

      this.$modal.msgWarning("功能开发中....")
      return

      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有组织管理矩阵人员落位表 数据项?').then(() => {
        this.exportLoading = true;
        return exportOporgManagerMatrixConfigExcel(params);
      }).then(response => {
        this.$download.excel(response, '组织管理矩阵人员落位表 .xls');
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    handleEditPerson(row, column, cell) {
      this.editTableRows = row
      this.editTableCell = column
      if (!!this.orgManagerDefineMap[column.property]
        && this.orgManagerDefineMap[column.property].orgKindId.indexOf(row.orgKindId) > -1
      ) {
        this.openConfigDialog = true
        this.editConfigInfo = {
          matrixId: this.matrixId,
          orgId: row.id,
          orgFullId: row.fullId,
          orgName: row.fullName,
          orgKindId: row.orgKindId,
          id: row[column.property] && row[column.property].id,
          managerDefineId: this.orgManagerDefineMap[column.property].code,
          managerDefineName: this.orgManagerDefineMap[column.property].name,
          dataValues: [...row[column.property] && row[column.property].dataValues || []]
        }
      }
    },
    // 保存人员配置
    submitConfigForm() {
      let cloneConfigForm = Object.assign({}, this.editConfigInfo)
      let dataValue = []
      if (cloneConfigForm.dataValues && cloneConfigForm.dataValues.length > 0) {
        cloneConfigForm.dataValues.forEach(item => {
          dataValue.push(item)
        })
      }
      cloneConfigForm.dataValues = dataValue.length > 0 ? JSON.stringify(dataValue) : ''
      if (cloneConfigForm.id != null) {
        updateOporgManagerMatrixConfig(cloneConfigForm).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.openConfigDialog = false
          this.editTableRows[this.editTableCell.property] = this.editConfigInfo
          this.refreshColumn = false
          this.$nextTick(() => {
            this.refreshColumn = true
          })
        });
        return;
      }
      // 添加的提交
      createOporgManagerMatrixConfig(cloneConfigForm).then(response => {
        this.$modal.msgSuccess("新增成功");
        this.open = false;
        this.openConfigDialog = false
        this.editConfigInfo.id = response.data
        this.editTableRows[this.editTableCell.property] = this.editConfigInfo
        this.refreshColumn = false
        this.$nextTick(() => {
          this.refreshColumn = true
        })
      });
    },
    closeConfigDialog() {
      this.openConfigDialog = false
    },
    // 删除配置中的人员
    handleDeleteConfigPerson(id) {
      let newData = []
      this.editConfigInfo.dataValues.forEach(item => {
        if (id != item.orgId) {
          newData.push(item)
        }
      })
      this.editConfigInfo.dataValues = newData
    },
    handleUserPicker() {
      this.openUserPicker = true
    },
    handleCopyDataValues() {
      this.copyDataValues = [...this.editConfigInfo.dataValues]
    },
    handlePasteDataValues() {
      this.editConfigInfo.dataValues = [...this.copyDataValues]
    },
    getUserList(userList) {
      this.editConfigInfo.dataValues = this.editConfigInfo.dataValues || []
      let existsDataValues = {}
      this.editConfigInfo.dataValues.forEach(item => {
        existsDataValues[item.orgId] = item
      })
      userList.forEach(item => {
        let d = {
          orgKindId: item.orgKindId,
          orgId: item.id,
          orgFullId: item.fullId,
          orgName: item.name,
          orgFullName: item.fullName
        }
        !existsDataValues[item.id] && this.editConfigInfo.dataValues.push(d)
      })
    },
    // 打开矩阵验证窗口
    handleTestMatrix() {
      this.openTestDialog = true
    },
    // 打开人员选择窗口
    handleChooseOrg() {
      this.openTestUserPicker = true
    },
    // 搜索机构管理员
    handleQueryMatrixPerson() {
      this.testParams.matrixId = this.matrixId
      this.testTableLoading = true
      getOrgManagerMatrixPerson(this.testParams).then(response => {
        let tableData = response.data && response.data.personList || []
        tableData.forEach(item => {
          item['managerOrgName'] = response.data.matrixConfig.orgName
        })
        this.testMatrixPersonList = response.data && response.data.personList || []
        this.testTableLoading = false
      }).finally(e => {
        this.testTableLoading = false
      });
    },
    // 重置矩阵测试查询条件
    resetTestQuery() {
      this.testParams = {}
    },
    // 关闭测试窗口
    closeTestDialog() {
      this.openTestDialog = false
    },
    testOrgChooseConfig(orgList) {
      if (orgList && orgList.length > 0) {
        this.testParams.orgId = orgList[0].id
        this.testParams.orgName = orgList[0].name
      }
    }
  }
};
</script>
